'''
Created on 2013-01-21

@author: levi
'''

import pydot
import datetime


def graph_to_dot(name, g):
    """
    build a dot file from a himesis graph
    """
    vattr=''
    nodes = {}
    graph = pydot.Dot(name, graph_type='digraph')
    dateTag = datetime.datetime.now().strftime("%Y-%b-%d_%H-%M-%S")
    for v in g.vs:
        vattr += str(v['name'])                                                                                                                                                                                     
        vattr += ' < '
        vattr += str(v['mm__']) 
        vattr += ' < '        
        vattr += str(v['GUID__'])[-12:]
#        print vattr     
        nodes[v.index] = pydot.Node(vattr)
        graph.add_node(nodes[v.index])
        vattr = ''
    for e in g.es:
        graph.add_edge(pydot.Edge(nodes[e.source],nodes[e.target]))
#    graph.write('/home/levi/Desktop/STATE%s%s.svg'%(key,dateTag))    
    graph.write('/home/levi/Desktop/%s.dot'%name)
    
    
    
def merge_models(first, second):
    """
    merge two himesis graphs
    IMPORTANT: only makes sense if the graphs are instances of the same metamodel
    """
    nb_nodes_first = len(first.vs)
    for index_v in range(len(second.vs)):
        first.add_node()
        first.vs[nb_nodes_first + index_v]['mm__'] = second.vs[index_v]['mm__']   
        first.vs[nb_nodes_first + index_v]['name'] = second.vs[index_v]['name'] 
    for index_e in range(len(second.es)):
        first.add_edges((nb_nodes_first + second.es[index_e].tuple[0],nb_nodes_first + second.es[index_e].tuple[1]))
    return first
